from django.shortcuts import render
from .ser import *
from .models import *
from rest_framework.response import Response
from rest_framework.views import APIView
from django.core.paginator import Paginator


# Create your views here.

class DepaM(APIView):
    def post(self, request):
        ser = DepaSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code': 20010})

    def get(self, request):
        user = Department.objects.all()
        ser = DepaSer(user, many=True)
        return Response({'code': 200, 'list': ser.data})


class Login(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = User.objects.filter(username=username).first()
        if user:
            if password == user.password:
                return Response({'code': 200, 'userid': user.id, 'types': user.authority})
            else:
                return Response({'code': 20010, 'mes': '密码错误'})
        else:
            return Response({'code': 20011, 'mes': '用户名错误'})


class UserM(APIView):
    def post(self, request):
        ser = UserSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code': 20010})

    def get(self, request):
        name = request.GET.get('name')
        if not name:
            cpage = request.GET.get('cpage')
            user = User.objects.all()
            p = Paginator(user, 3)
            users = p.page(cpage)
            ser = SUserSer(users, many=True)
            return Response({'code': 200, 'list': ser.data, 'tpage': p.num_pages})
        else:
            depa = User.objects.filter(username=name).all()
            ser = SUserSer(depa, many=True)
            return Response({'code': 200, 'list': ser.data})


class BcateM(APIView):
    def get(self, request):
        id = request.GET.get('id')
        if not id:
            bcate = Bcate.objects.all()
            ser = BcateSer(bcate, many=True)
            return Response({'code': 200, 'list': ser.data})
        else:
            book = Book.objects.filter(cate_id=id).all()
            ser = BookSer(book, many=True)
            return Response({'code': 200, 'list': ser.data})


class BookM(APIView):
    def get(self, request):
        name = request.GET.get('name')
        if name:
            book = Book.objects.filter(name=name).all()
            ser = BookSer(book, many=True)
            return Response({'code': 200, 'list': ser.data})
        else:
            cpage = request.GET.get('cpage')
            book = Book.objects.all()
            p = Paginator(book, 4)
            books = p.page(cpage)
            ser = BookSer(books, many=True)
            return Response({'code': 200, 'list': ser.data, 'tpage': p.num_pages})


class Pai(APIView):
    def get(self, request):
        types = request.GET.get('types')
        if types == '1':
            book = Book.objects.order_by('-price')
            types = 2
            ser = BookSer(book, many=True)
            return Response({'code': 200, 'list': ser.data, 'types': types})

        elif types == '2':
            book = Book.objects.order_by('price')
            types = 1
            ser = BookSer(book, many=True)
            return Response({'code': 200, 'list': ser.data, 'types': types})


import re


class Regi(APIView):
    def post(self, request):
        # 账号
        username = request.data.get('username')
        # 1判断是否为空
        if not username:
            return Response({'code': 10010})
        # 2判断符合规则
        name = re.match('\w{5,12}$', username)
        if not name:
            return Response({'code': 10011})
        # 3判断是否唯一
        names = RedisUser.objects.filter(username=username).first()
        if names:
            return Response({'code': 10012})

        # 密码
        password = request.data.get('password')
        # 1判断是否为空
        if not password:
            return Response({'code': 10013})
        # 2判断符合规则
        name = re.match('\w{6,10}$', password)
        if not name:
            return Response({'code': 10014})

            # 手机号
        mobile = request.data.get('mobile')
        # 1判断是否为空
        if not mobile:
            return Response({'code': 10015})
            # 2判断符合规则
        mobile = re.match('^1[3-9]\d{9}$', mobile)
        if not mobile:
            return Response({'code': 10016})
            # 3判断是否唯一
        mobiles = RedisUser.objects.filter(mobile=mobile).first()
        if mobiles:
            return Response({'code': 10017})

        return Response({'code': 200})


import random
from utils.comm import send_message
from utils.comm import get_redis


class Note(APIView):
    def post(self, request):
        mobile = request.data.get('mobile')
        codes = random.randint(100000, 999999)
        res = send_message(mobile, str(codes), 1)
        code = 10010
        if res:
            code = 200
            coon = get_redis()
            coon.setex(mobile, 60, codes)
        return Response({'code': code})


from django.contrib.auth.hashers import make_password, check_password


class UserMM(APIView):
    def post(self, request):

        request.data['password'] = make_password(request.data.get('password'))
        mobile = request.data.get('mobile')
        codes = request.data.get('codes')
        conn = get_redis()
        codess = conn.get(mobile)
        if codess:
            codess = str(codess, encoding='utf8')
        if codes == codess:
            ser = SsuserSer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({'code': 200})
            else:
                print(ser.errors)
                return Response({'code': 20010})
        else:
            return Response({'code': 10018})


from django.core.paginator import Paginator


class NewsM(APIView):
    def get(self, request):
        id = request.GET.get('id')
        if not id:
            cpage = request.GET.get('cpage')
            news = News.objects.all()
            p = Paginator(news, 2)
            newss = p.page(cpage)

            ser = NewsSer(newss, many=True)
            return Response({'code': 200, 'list': ser.data, 'tpage': p.num_pages})
        else:
            news = News.objects.filter(id=id).first()
            ser = NewsSer(news)
            return Response({'code': 200, 'list': ser.data})

    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = RedisUser.objects.filter(username=username).first()
        if user:
            if check_password(password, user.password):
                return Response({'code': 200, 'userid': user.id})
            else:
                return Response({'code': 20010, 'mes': '密码错误'})
        else:
            return Response({'code': 20011, 'mes': '用户名错误'})


class Quanxian(APIView):
    def post(self, request):
        userid = request.data.get('userid')
        newsid = request.data.get('newsid')

        conn = get_redis()
        # key = str(userid) + ',' + str(newsid)
        conn.hset(userid, newsid, 1)
        count = conn.hget(userid, newsid)
        if count:
            count = int(count)
        if count <= 3:
            conn.hincrby(userid, newsid)
            return Response({'code': 200})
        else:
            return Response({'code': 20010})

        # conuts = conn.hincrby(userid, newsid)
        # if conuts:
        #     conuts = int(conuts)
        # if conuts <= 3:
        #
        #     return Response({'code': 200})
        #
        # return Response({'code': 20010})


class CateM(APIView):
    def post(self, request):
        ser = CateSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code': 20010})

    def get(self, request):
        cate = Cate.objects.all()
        ser = CateSer(cate, many=True)
        return Response({'code': 200, 'list': ser.data})


class ShopM(APIView):
    def post(self, request):
        ser = ShopSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code': 20010})

    def get(self, request):
        sorted = request.GET.get('sorted')
        if not sorted:
            shop = Shop.objects.all()
            ser = ShowShopSer(shop, many=True)
            return Response({'code': 200, 'list': ser.data})
        else:
            shop = Shop.objects.order_by('-'+sorted).all()
            ser = ShowShopSer(shop, many=True)
            return Response({'code': 200, 'list': ser.data})
